package svc

import (
	"activity_srv/activityclient"
	"api/internal/config"
	"api/internal/middleware"
	"collection_srv/collectionclient"
	"device_srv/deviceclient"
	"github.com/go-pay/gopay/alipay"
	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/rest"
	"github.com/zeromicro/go-zero/zrpc"
	"homepage_srv/homepageclient"
	"order_srv/orderclient"
	"user_srv/userclient"
)

type ServiceContext struct {
	Config              config.Config
	UserRpc             userclient.User
	DeviceRpc           deviceclient.Device
	Collection          collectionclient.Collection
	HomepageGrpc        homepageclient.Homepage
	UserAgentMiddleware rest.Middleware
	OrderRpc            orderclient.Order
	ActivityRpc         activityclient.Activity
	Alipay              *alipay.Client
}

func NewServiceContext(c config.Config) *ServiceContext {
	client, err := alipay.NewClient( //初始化
		c.AliPay.AppId,
		c.AliPay.PrivateKey,
		false, // 沙箱环境
	)
	// ✅ 启用自动验签（只支持公钥文本）
	client.AutoVerifySign([]byte(c.AliPay.PublicKey))
	if err != nil {
		logx.Errorf("支付宝初始化失败", err)
	}
	logx.Infof("// ✅ 支付宝初始化成功")
	return &ServiceContext{
		Config:              c,
		UserRpc:             userclient.NewUser(zrpc.MustNewClient(c.UserRpc)),
		DeviceRpc:           deviceclient.NewDevice(zrpc.MustNewClient(c.DeviceRpc)),
		Collection:          collectionclient.NewCollection(zrpc.MustNewClient(c.CollectionRpc)),
		HomepageGrpc:        homepageclient.NewHomepage(zrpc.MustNewClient(c.HomepageRpc)),
		UserAgentMiddleware: middleware.NewUserAgentMiddleware().Handle,
		OrderRpc:            orderclient.NewOrder(zrpc.MustNewClient(c.OrderRpc)),
		ActivityRpc:         activityclient.NewActivity(zrpc.MustNewClient(c.ActivityRpc)),
		Alipay:              client,
	}

}
